import { defineStore } from 'pinia';
import { ref } from 'vue';
import request from '@/utils/request';
import { showNotification } from '@/utils/notify';
import  type {Menu} from '@/types/menu'


type MyRequest = {
  code: number;
  message: string;
  data: Menu[];
}

export const useMenuStore = defineStore('menu-store', () => {
  // 存储角色菜单数据
  const menus = ref<Menu[]>([]);

  // 用于存储菜单树状结构数据
    const menuTreeData = ref<Menu[]>([]);

  // 获取菜单树状结构数据
  const fetchTreeMenus = async () => {
    try {
      const { code, data, message } = await request.get<MyRequest>(`/api/sys-menu/all`);
      if (code === 200) {
        menuTreeData.value = data;
        
      } else {
        showNotification(message, true);
      }
    } catch (error) {
      showNotification('获取树状菜单数据失败', true);
    }
  };

  const fetchMenus = async () => {
    try {
      const { code, data, message } = await request.get<MyRequest>(`/api/sys-menu/findNodes`); 
      menus.value = data;
    } catch (error) {
      showNotification('获取菜单数据失败', true);
    }
  }
  // 添加角色菜单
  const addMenu = async (menu: Menu) => {
    try {
      const { code, message } = await request.post<{ code: number; message: string }>('api/sys-menu/save', menu);
      if (code === 200) {
        showNotification('菜单添加成功');
        await fetchTreeMenus();
      } else {
        showNotification(message, true);
      }
    } catch (error) {
      showNotification('菜单添加失败', true);
      console.error('添加菜单时出错:', error);
    }
  };

  // 更新角色菜单
  const updateMenu = async (menu: Menu) => {
    try {
      const { code, message } = await request.put<{ code: number; message: string }>('api/sys-menu/update', menu);
      if (code === 200) {
        showNotification('菜单更新成功');
        await fetchTreeMenus();
      } else {
        showNotification(message, true);
      }
    } catch (error) {
      showNotification('菜单更新失败', true);
      console.error('更新菜单时出错:', error);
    }
  };

  // 删除角色菜单
  const deleteMenu = async (id: string) => {
    try {
      const { code, message } = await request.post<{ code: number; message: string }>(`api/sys-menu/remove/${id}`);
      if (code === 200) {
        showNotification('菜单删除成功');
        await fetchTreeMenus();
      } else {
        showNotification(message, true);
      }
    } catch (error) {
      showNotification('菜单删除失败', true);
      console.error('删除菜单时出错:', error);
    }
  };



  onMounted(() => {
    fetchMenus()
    fetchTreeMenus(); 
  })
  return {
    menus,
    menuTreeData,  
    addMenu,
    updateMenu,
    deleteMenu,
    fetchTreeMenus
  };
});
    